using UnityEngine;
using UnityEditor;
using UnityEngine.Rendering;


[CustomEditor(typeof(EffectOrderContainer))]
public class EffectOrderContainerEditor : UnityEditor.Editor
{
    public override void OnInspectorGUI()
    {
        base.OnInspectorGUI();
        EditorGUILayout.Space(20);
        var orderContainer = this.target as EffectOrderContainer;
        GUILayout.Label("order = " + orderContainer.BaseOrder);
        if (GUILayout.Button("重新记录所有渲染节点", GUILayout.Width(150), GUILayout.Height(50)))
        {
            FillOrderData(orderContainer);
            EditorUtility.SetDirty(target);
        }
    }

    public static void FillOrderData(EffectOrderContainer containerComp)
    {
        containerComp.renderList.Clear();

        var childRenderArr = containerComp.gameObject.GetComponentsInChildren<Renderer>(true);
        foreach (var childRender in childRenderArr)
        {
            if (childRender.gameObject.layer == GameLayer.EffectMask)
            {
                continue;
            }
            var renderObj = new EffectRenderObj();
            renderObj.renderer = childRender;
            renderObj.order = childRender.sortingOrder;
            containerComp.renderList.Add(renderObj);
        }

        var sortingGroupArr = containerComp.gameObject.GetComponentsInChildren<SortingGroup>();
        foreach (var sortingGroup in sortingGroupArr)
        {
	        if (sortingGroup.gameObject.layer == GameLayer.EffectMask)
	        {
		        continue;
	        }
            var renderObj = new EffectRenderObj();
	        renderObj.sortingGroup = sortingGroup;
	        renderObj.order = sortingGroup.sortingOrder;
	        containerComp.renderList.Add(renderObj);
        }
    }

    public static void AddOffset(GameObject go, int addOffset)
    {
        var childRenderArr = go.GetComponentsInChildren<Renderer>(true);
        foreach (var childRender in childRenderArr)
        {
            if (childRender.gameObject.layer == GameLayer.EffectMask)
            {
                continue;
            }
            childRender.sortingOrder = childRender.sortingOrder + addOffset;
        }
    }
}
